package 网络编程项目.login.utiles;



import 网络编程项目.pojo.Message;
import 网络编程项目.pojo.Response;
import 网络编程项目.util.ObjectUtils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class ClientUtil {
//  private static String HOST = "127.0.0.1";
//  private static int PORT = 8080;
//  public static SocketChannel socketChannel = getSocketChannel();
//
//  private static SocketChannel getSocketChannel() {
//    if (socketChannel == null) {
//      try {
//        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
//      } catch (IOException e) {
//        e.printStackTrace();
//      }
//    }
//    return socketChannel;
//  }

  public void sendMessage(SocketChannel socketChannel, Message message) {
    try {
      byte[] str = ObjectUtils.serialize(message);
      ByteBuffer buffer = ByteBuffer.wrap(str);
      socketChannel.write(buffer);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public Response getResponse(SocketChannel socketChannel) {
    Response response = new Response();
    try {
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      int len = socketChannel.read(buffer);
      buffer.flip();
      String str = new String(buffer.array(), 0, len);
      response = ObjectUtils.deserialize(str.getBytes());
    } catch (IOException | ClassNotFoundException e) {
      e.printStackTrace();
    }
    return response;
  }
}
